//
//  LCCheckTrackViewController.swift
//  mggz
//
//  Created by QinWei on 2018/1/12.
//  Copyright © 2018年 爱丽丝的梦境. All rights reserved.
//

import UIKit
import ObjectMapper
class LCCheckTrackViewController: BaseViewController{
    
    @IBOutlet weak var stepView: UIView!
    @IBOutlet weak var topView: UIView!
    
    @IBOutlet weak var projectName: UILabel!
    
    @IBOutlet weak var startTime: UILabel!
    
    @IBOutlet weak var endTime: UILabel!
    
    @IBOutlet weak var stateLabel: UILabel!
    
    @IBOutlet weak var checkoutLabel: UILabel!
    
    @IBAction func zoomAdd(_ sender: Any) {
        if (zoomValue! > 3 || zoomValue! == 3 ) && (zoomValue! < 21){
            zoomValue! += 0.5
            mapView.zoomLevel = zoomValue!
        }
    }
    
    
    @IBAction func reduceZomm(_ sender: Any) {
        if (zoomValue! > 3 ) && (zoomValue! < 21 || zoomValue! == 21 ){
            zoomValue! -= 0.5
            mapView.zoomLevel = zoomValue!
        }
    }
    
    
    
    
    var colorfulPolyline: BMKPolyline?
    var zoomValue : Float?
    var lcnowTime:String?
    let latArray = ["29.921237","29.922337","29.923437","29.924537"]
    let lonArray = ["121.617652","121.617652","121.617652","121.617652"]
    var companyAnnotation : BMKPointAnnotation?
    
    var startAnnotation : MWPointAnnotation?
    var stopAnnotation : MWPointAnnotation?
    var endAnnotation : MWPointAnnotation?
    var normalAnnotation : MWPointAnnotation?
    
    fileprivate var locationService : BMKLocationService?
    fileprivate lazy var mapView : BMKMapView = {
        let mapView = BMKMapView()
        mapView.frame = CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT)
        
        let param = BMKLocationViewDisplayParam()
        param.isAccuracyCircleShow = false
        param.locationViewOffsetX = 0
        param.isRotateAngleValid = false
        param.locationViewImgName = "民工位置"
        mapView.updateLocationView(with: param)
        return mapView
    }()
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        mapView.viewWillAppear()
        locationService?.delegate = self
        mapView.delegate = self
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        locationService?.delegate = nil
        mapView.delegate = nil
        mapView.viewWillDisappear()
    }
    
    //左右滑动月份时触发
    var currentMonthChangeHandler: ((Date) -> Void)?
    var selectDateHandler: ((Date) -> Void)?
    
    var currentProject: LCProjectListModel? {
        willSet {
            self.currentProject = newValue
        }
    }
    var personInformation: MWCurrentLocationModel? {
        willSet {
            self.personInformation = newValue
        }
    }
    var workerModel : LCMWTrackPersonModel?
    fileprivate var calendarView : LCCalendarView = {
        let calendarView = LCCalendarView.initLCCalendarView(size: CGSize(width: SCREEN_WIDTH, height: 360))
        return calendarView
    }()
    lazy var itemArray : [LCMWTrackModel] = [LCMWTrackModel]()
    lazy var colorIndexArray : [Int] = [Int]()
    lazy var coordsArray:[CLLocationCoordinate2D] = [CLLocationCoordinate2D]()
    override func viewDidLoad() {
        super.viewDidLoad()
        self.mapView.delegate = self
        self.view.addSubview(mapView)
        self.zoomValue = 17
        mapView.zoomLevel = 17
        self.locationService = BMKLocationService()
        self.locationService?.delegate = self
//        self.locationService = BMKLocationService.init()
//        // self.locationService?.stopUserLocationService()
//        self.locationService?.startUserLocationService()
//        self.mapView.userTrackingMode = BMKUserTrackingModeFollow
        self.locationService?.startUserLocationService()
        self.locationService?.allowsBackgroundLocationUpdates = true
        self.mapView.showsUserLocation = false
        self.mapView.userTrackingMode = BMKUserTrackingModeFollow
        self.mapView.showsUserLocation = true
        
        self.setupInitUI()
        self.setupstepView()
        self.setupCompanyCenterLocation()
        self.setupData { (result) in
            self.setupTrackLocationData()
            self.setupTrackLocationAnimatationView()
        }
       
        
    }
    private func setupstepView(){
        self.stepView.layer.cornerRadius = 5
        self.stepView.layer.masksToBounds = true
        self.stepView.layer.borderWidth = 1
        self.stepView.layer.borderColor = UIColor.init(red: 0.97, green: 0.97, blue: 0.97, alpha: 1).cgColor
        self.stepView.layer.shadowColor = UIColor.init(red: 0, green: 0, blue: 0, alpha: 0.2).cgColor
        self.view.bringSubview(toFront: self.stepView)
    }
    fileprivate func setupTrackLocationAnimatationView(){
        for index in 0..<self.itemArray.count {
            let model = self.itemArray[index]
            guard  let lat = model.Latitude else{
                return
            }
            guard let lon = model.Longitude else{
                return
            }
            let doubleLat = Double(lat)
            let doubleLon = Double(lon)
            if index == 0{
                self.startAnnotation = MWPointAnnotation()
                self.startAnnotation?.mwTag = index
                self.startAnnotation?.title = ""
                self.startAnnotation?.coordinate = CLLocationCoordinate2DMake(doubleLat!, doubleLon!)
            self.mapView.addAnnotation(self.startAnnotation)
            }else if index==self.itemArray.count-1{
                self.endAnnotation = MWPointAnnotation()
                self.endAnnotation?.mwTag = index
                self.endAnnotation?.title = ""
                self.endAnnotation?.coordinate = CLLocationCoordinate2DMake(doubleLat!, doubleLon!)
                self.mapView.addAnnotation(self.endAnnotation)
            }else{
                if model.IsStayOut == true{
                    self.stopAnnotation = MWPointAnnotation()
                    self.stopAnnotation?.mwTag = index
                    self.stopAnnotation?.title = ""
                    self.stopAnnotation?.coordinate = CLLocationCoordinate2DMake(doubleLat!, doubleLon!)
                    self.mapView.addAnnotation(self.stopAnnotation)
                }else{
                    self.normalAnnotation = MWPointAnnotation()
                    self.normalAnnotation?.mwTag = index
                    self.normalAnnotation?.title = ""
                    self.normalAnnotation?.coordinate = CLLocationCoordinate2DMake(doubleLat!, doubleLon!)
                    self.mapView.addAnnotation(self.normalAnnotation)
                }
            }
        }
    }
    fileprivate func setupCompanyCenterLocation(){
        if let lat = currentProject?.Latitude, let lon = currentProject?.Longitude {
            var doubuleLat = lat.doubleValue ?? 0
            var doubleLon = lon.doubleValue ?? 0
                //通过百度地图的view添加大头针
                self.companyAnnotation = BMKPointAnnotation()
                var coor = CLLocationCoordinate2D()
                coor.latitude = doubuleLat
                coor.longitude = doubleLon
                self.companyAnnotation?.coordinate = coor
            self.mapView.addAnnotation( self.companyAnnotation)
                //将大头针放在地图中心
                self.mapView.setCenter(coor, animated: true)
                
                
                //设置显示范围
                let aRadius = currentProject?.SignedRange ?? 100
                let circle = BMKCircle(center: coor, radius: aRadius)
                self.mapView.add(circle)
                
            
        }
    }
    fileprivate func setupInitUI(){
        self.navigationItem.title = "异常轨迹"
        let nowTime = Date()
        let currentTime = mwDateToString(date: nowTime)
        self.lcnowTime = dateToString(date: nowTime)
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: currentTime, style: .plain, target: self, action: nil)
        view.bringSubview(toFront: topView)
}
    
    private func setupData(callBack:@escaping (Bool) ->Void){
        
        guard let accountId = WWUser.sharedInstance.accountId else{
            return
        }
        guard let MarketSupplyBaseID = self.currentProject?.MarketSupplyBaseID else{
            return
        }
        guard let DemandBaseMigrantWorkerID :String = self.personInformation?.ID else{
            return
        }
    LCAPiMainManager.request(.GetMWTrack(DemandBaseMigrantWorkerID: DemandBaseMigrantWorkerID, MarketSupplyBaseID: MarketSupplyBaseID, locateDate: lcnowTime!, IsShowDetail: true, AccountId: accountId), completion: { (result) in
        if case let .success(response) = result {
            guard  let jsonString :NSDictionary = try?response.mapJSON() as! NSDictionary else{
                return
            }
            guard (jsonString["State"]) as! String == "OK" else{
                return
            }
            let resultDic : NSDictionary = jsonString["Result"] as! NSDictionary
            guard let workerDic :NSDictionary = resultDic["MigrantWorker"] as? NSDictionary else{
                return 
            }
            self.workerModel = Mapper<LCMWTrackPersonModel>().map(JSONObject: workerDic)!
           // let locationList : NSArray = (resultDic["LocationList"] as? NSArray)!
            guard let locationList : NSArray = resultDic["LocationList"] as? NSArray else{
                  return
            }
            self.itemArray = Mapper<LCMWTrackModel>().mapArray(JSONObject: locationList)!
                print(self.itemArray)
                print(jsonString)
                callBack(true)
                return
        }else{
            callBack(false)
        }
    })
}
    fileprivate func setupTrackLocationData(){
        
        
        for index in 0..<self.itemArray.count{
            let model = self.itemArray[index]
            guard  let lat = model.Latitude else{
                return
            }
            guard let lon = model.Longitude else{
                return
            }
           let doubleLat = Double(lat)
           let doubleLon = Double(lon)
           self.coordsArray.append(CLLocationCoordinate2DMake(doubleLat!, doubleLon!))
            if index != 0{
                if model.IsLoss == true{
                   self.colorIndexArray.append(1)
                }else{
                    self.colorIndexArray.append(0)
                }
            }
        }
        // 添加折线(分段颜色绘制)覆盖物
        if colorfulPolyline == nil {
//构建BMKPolyline,使用分段颜色索引，其对应的BMKPolylineView必须设置colors属性
            colorfulPolyline = BMKPolyline(coordinates: &self.coordsArray, count: UInt(self.itemArray.count), textureIndex: self.colorIndexArray)
        }
        self.mapView.add(colorfulPolyline)
    }
}

extension LCCheckTrackViewController:BMKMapViewDelegate,BMKLocationServiceDelegate{
    func mapView(_ mapView: BMKMapView!, viewFor overlay: BMKOverlay!) -> BMKOverlayView! {
        if (overlay as? BMKCircle) != nil {
            let circleView = BMKCircleView(overlay: overlay)
            circleView?.fillColor = colorWith255RGBA(16, g: 142, b: 233, a: 0.2)
            circleView?.strokeColor = colorWith255RGBA(16, g: 142, b: 233, a: 1)
            circleView?.lineWidth = 1
            
            return circleView
        }
        
        if let overlayTemp = overlay as? BMKPolyline {
            let polylineView = BMKPolylineView(overlay: overlay)
            if overlayTemp == colorfulPolyline {
                polylineView?.lineWidth = 2
                /// 使用分段颜色绘制时，必须设置（内容必须为UIColor）
                polylineView?.colors = [UIColor(red: 0.31, green: 0.89, blue: 0.76, alpha: 1),UIColor(red: 0.99, green: 0.31, blue: 0.23, alpha: 1)]
            }
            return polylineView
        }
        
        return UIView() as! BMKOverlayView
    }
    func mapView(_ mapView: BMKMapView!, viewFor annotation: BMKAnnotation!) -> BMKAnnotationView! {
        if(annotation as! BMKPointAnnotation) == companyAnnotation{
            let AnnotationViewID = "renameMark"
            var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: AnnotationViewID) as! BMKPinAnnotationView?
            if annotationView == nil {
                annotationView = BMKPinAnnotationView(annotation: annotation, reuseIdentifier: AnnotationViewID)
                annotationView?.image = UIImage(named: "企业位置")
                annotationView?.frame = CGRect(x: 0, y: 0, width: 30, height: 39)//大头针大小，根据图片宽高比等比配置
                
                annotationView?.annotation = annotation
                return annotationView
            }
        }
        
        if annotation.isKind(of: MWPointAnnotation.self){
            
                let mwAnnotationViewID = "start"
                var mwAnnotationView = mapView.dequeueReusableAnnotationView(withIdentifier: mwAnnotationViewID) as! LCMWAnnotationView?
                if mwAnnotationView == nil {
                    mwAnnotationView = LCMWAnnotationView(annotation: annotation, reuseIdentifier: mwAnnotationViewID)
                }
            if(annotation as! MWPointAnnotation) == startAnnotation{
                mwAnnotationView?.image = UIImage.init(named: "track_start");
            }else if(annotation as! MWPointAnnotation) == stopAnnotation{
                mwAnnotationView?.image = UIImage.init(named: "track_stop");
            }else if(annotation as! MWPointAnnotation) == endAnnotation{
                mwAnnotationView?.image = UIImage.init(named: "track_end");
            }else if(annotation as! MWPointAnnotation) == normalAnnotation{
                mwAnnotationView?.image = UIImage.init(named: "Icon_地址");
            }
            let selectAnnotation = annotation as! MWPointAnnotation
            let markModel = self.itemArray[selectAnnotation.mwTag!]
            mwAnnotationView?.frame = CGRect(x: (mwAnnotationView?.frame.origin.x)!, y: (mwAnnotationView?.frame.origin.y)!, width: 50, height: 50)
            let callView = LCTrackCalloutView(frame: CGRect(x: 0, y: 0, width: 220, height: 81))
            
            if markModel.IsLoss == true{
               let startStr = markModel.LossBeginTime
               let endStr = markModel.LossEndTime
                callView.timeLabel.text = startStr! + "——" + endStr!
                callView.stateLabel.text = "失联中"
            }else if markModel.IsStayOut == true{
                let startStr = markModel.StayOutBeginTime
                let endStr = markModel.StayOutEndTime
                callView.timeLabel.text = startStr! + "——" + endStr!
                callView.stateLabel.text = "停留中"
            }else{
                
                callView.stateLabel.text = "状态正常"
            }
            let popView = BMKActionPaopaoView(customView: callView)
            mwAnnotationView?.paopaoView = nil
            mwAnnotationView?.paopaoView = popView
            return mwAnnotationView
            
            /*
            if(annotation as! BMKPointAnnotation) == stopAnnotation{
                let mwAnnotationViewID = "stop"
                var mwAnnotationView = mapView.dequeueReusableAnnotationView(withIdentifier: mwAnnotationViewID) as! LCMWAnnotationView?
                if mwAnnotationView == nil {
                    mwAnnotationView = LCMWAnnotationView(annotation: annotation, reuseIdentifier: mwAnnotationViewID)
                }
                mwAnnotationView?.image = UIImage.init(named: "track_stop");
                mwAnnotationView?.frame = CGRect(x: (mwAnnotationView?.frame.origin.x)!, y: (mwAnnotationView?.frame.origin.y)!, width: 50, height: 50)
                let callView = LCCalloutView(frame: CGRect(x: 0, y: 0, width: 220, height: 160))
                let popView = BMKActionPaopaoView(customView: callView)
                mwAnnotationView?.paopaoView = nil
                mwAnnotationView?.paopaoView = popView
                return mwAnnotationView
            }
            if(annotation as! BMKPointAnnotation) == endAnnotation{
                let mwAnnotationViewID = "end"
                var mwAnnotationView = mapView.dequeueReusableAnnotationView(withIdentifier: mwAnnotationViewID) as! LCMWAnnotationView?
                if mwAnnotationView == nil {
                    mwAnnotationView = LCMWAnnotationView(annotation: annotation, reuseIdentifier: mwAnnotationViewID)
                }
                mwAnnotationView?.image = UIImage.init(named: "track_end");
                mwAnnotationView?.frame = CGRect(x: (mwAnnotationView?.frame.origin.x)!, y: (mwAnnotationView?.frame.origin.y)!, width: 50, height: 50)
                let callView = LCCalloutView(frame: CGRect(x: 0, y: 0, width: 220, height: 160))
                let popView = BMKActionPaopaoView(customView: callView)
                mwAnnotationView?.paopaoView = nil
                mwAnnotationView?.paopaoView = popView
                return mwAnnotationView
            }
            
            
            if(annotation as! BMKPointAnnotation) == normalAnnotation{
                let mwAnnotationViewID = "normal"
                var mwAnnotationView = mapView.dequeueReusableAnnotationView(withIdentifier: mwAnnotationViewID) as! LCMWAnnotationView?
                if mwAnnotationView == nil {
                    mwAnnotationView = LCMWAnnotationView(annotation: annotation, reuseIdentifier: mwAnnotationViewID)
                }
                mwAnnotationView?.image = UIImage.init(named: "Icon_地址");
                mwAnnotationView?.frame = CGRect(x: (mwAnnotationView?.frame.origin.x)!, y: (mwAnnotationView?.frame.origin.y)!, width: 50, height: 50)
                let callView = LCCalloutView(frame: CGRect(x: 0, y: 0, width: 220, height: 160))
                let popView = BMKActionPaopaoView(customView: callView)
                mwAnnotationView?.paopaoView = nil
                mwAnnotationView?.paopaoView = popView
                return mwAnnotationView
            }
 */
        }

        return nil
    }
    func mapViewDidFinishLoading(_ mapView: BMKMapView!) {
        
    }
    func mapView(_ mapView: BMKMapView!, didAddAnnotationViews views: [Any]!){
        
    }
    func mapViewDidFinishRendering(_ mapView: BMKMapView!) {
        WWProgressHUD.dismiss()
    }
}




















